package com.wzcl.app.common;

import com.alibaba.fastjson.JSON;
import com.wzcl.app.dao.model.Delivery;
import com.wzcl.app.dao.model.Orders;
import com.wzcl.app.dao.repository.OrdersRepository;
import com.wzcl.app.model.common.WZCL;
import com.wzcl.app.model.dto.DeliveryDto;
import com.wzcl.app.service.DeliveryService;
import com.wzcl.app.utils.DateUtil;
import com.wzcl.app.utils.SpringUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Log4j2
public class ScheduledTask{
    public static final int DELIVERY_MAX_DAY = 20;

    @Resource
    private OrdersRepository ordersRepository;

    @Scheduled(cron = "0 0 5 * * ?")
    public void scheduledTask1(){
        DeliveryService deliveryService = (DeliveryService) SpringUtil.getBean("deliveryServiceImpl");
        DeliveryDto deliveryDto = new DeliveryDto();
        deliveryDto.setDeliveryState(WZCL.DELIVERY_STATE.BE_RECEIVED);
        List<Delivery> deliveryList = deliveryService.getDeliveryList(deliveryDto);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,-DELIVERY_MAX_DAY);
        Date time = instance.getTime();
        if(deliveryList != null && deliveryList.size()>0){
            deliveryList = deliveryList.stream().filter(delivery -> time.before(delivery.getSendTime())).collect(Collectors.toList());
        }
        if(deliveryList != null && deliveryList.size()>0){
            log.info("Delivery {} is overTime. Automatic confirm receipt",JSON.toJSONString(deliveryList));
            for (Delivery delivery : deliveryList) {
                deliveryService.confirm(delivery.getId(),null);
            }
        }
    }

    // 每隔5分钟请求一次，如果有订单超过30分钟未支付则将未支付订单改为取消
    @Scheduled(cron = "0 */5 * * * ?")
    public void fixedDelay() {
        //查询所有未支付的有效订单创建时间
        List<Orders> allUsers = ordersRepository.findAllPayState();
        //获取系统当前时间进行遍历比较，如果有则更新状态
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        for (int index = 0; index < allUsers.size(); index++) {
            //获取Date类型的分钟数进行比较
            if (DateUtil.getMinute(date) - 30 > DateUtil.getMinute(allUsers.get(index).getCreateTime()) && allUsers.get(index).getPayState() != 1){
                // 如果是30分钟之前的订单，那么进行状态更新，变为取消
                // 修改订单状态
                ordersRepository.updateOrderStateByPhone(allUsers.get(index).getUserPhone());
            }
        }
    }
}
